﻿using MesBSW.BLL.Mes;
using MesBSW.BLL.Role;
using MesBSW.DAL.MesDB;
using MesBSW.DAL.RoleDTO;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace MesBSW.View
{

    public partial class LoginFrm : UILoginForm
    {
        private LanguageControler _ctrl = new LanguageControler();
        private List<LanguageInfo> _lang_list = new List<LanguageInfo>();

        public LanguageInfo CurrLanguage = null;
        public BaseUserDTO tmpBean = null;
        
        public LoginFrm()
        {
            InitializeComponent();
        }

        private void LoginFrm_ButtonLoginClick(object sender, System.EventArgs e)
        {
            
            HomeControler myCtrl = new HomeControler();

            if (UserName == null || UserName.ToString().Trim().Equals(""))
            {
                UIMessageBox.ShowError("用户帐号为空！", true, false);
            }
            else if (this.cmbLanguage.SelectedValue is null)
            {
                UIMessageBox.ShowError("请选择语言！", true, false);
            }
            else
            {

                try
                {
                    if (this._lang_list != null && this._lang_list.Count > 0)
                    {
                        var query = this._lang_list.Where(q => q.lang_code == this.cmbLanguage.SelectedValue.ToString());
                        this.CurrLanguage = query != null && query.Count() > 0 ? query.First<LanguageInfo>() : null; 
                    }
                    tmpBean = myCtrl.Login(UserName.ToString().Trim(), Password.ToString().Trim());
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                catch (Exception ex)
                {
                    UIMessageBox.ShowError("登陆失败！" + "\r\n" + ex.Message, true, false);
                }
            }
        }

        private void LoginFrm_Load(object sender, EventArgs e)
        {
            this.cmbLanguage.Items.Clear();

            this._lang_list = this._ctrl.SearchAllLanguageInfo();
            DataTable tmpDt = new DataTable();
            tmpDt.Columns.Add("code", typeof(string));
            tmpDt.Columns.Add("name", typeof(string));

            if (this._lang_list != null && this._lang_list.Count > 0)
            {   
                foreach (var tmpLanguage in this._lang_list)
                {
                    DataRow tmpRow = tmpDt.NewRow();
                    tmpRow["code"] = tmpLanguage.lang_code;
                    tmpRow["name"] = tmpLanguage.lang_name_cn + (string.IsNullOrEmpty(tmpLanguage.lang_name_en) ? "" : $"({tmpLanguage.lang_name_en})");
                    tmpDt.Rows.Add(tmpRow);
                }
            }

            this.cmbLanguage.DataSource = tmpDt;
            this.cmbLanguage.DisplayMember = "name";
            this.cmbLanguage.ValueMember = "code";
        }
    }
}